package com.hl.hospital.controller;

import com.hl.hospital.config.Constants;
import com.hl.hospital.config.CookieUtils;
import com.hl.hospital.dao.UserfiveMapper;
import com.hl.hospital.entity.Userfive;
import com.hl.hospital.service.impl.UserServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: hl
 * @Date: 2021/06/23/19:28
 */
@Controller
public class LoginController extends HttpServlet {
    private static final String COOKIE_INFO_USER_NAME="userInfo";//cookie
    @Autowired
    private UserServiceImpl userService;
    @RequestMapping(value = {"/","/login"},method = RequestMethod.GET)
    public String login(HttpServletRequest req, HttpServletResponse resp){
        String userInfo= CookieUtils.getCookieValue(req,COOKIE_INFO_USER_NAME);
        if(!StringUtils.isBlank(userInfo))
        {
            String [] arry=userInfo.split(":");
            String jobnumber=arry[0];
            String password=arry[1];
            req.setAttribute("username",jobnumber);
            req.setAttribute("password",password);
            req.setAttribute("isRemember","true");
        }
        return "login";
    }

    @RequestMapping(value = "login",method = RequestMethod.POST )
    public  String login(@RequestParam(required = true) String  username, @RequestParam(required = true) String password, HttpServletRequest httpServletRequest, HttpServletResponse resp){

        boolean  isRemember=httpServletRequest.getParameter("isRemember")==null? false:true;
        Userfive user=userService.login(username,password);
        //登陆失败
        if (user==null)
        {
            httpServletRequest.setAttribute("message","用户名或者密码错误");
            return "login";
        }
        //登录成功
        else{
            //将登陆信息放入会话
            if(isRemember)
            {
                CookieUtils.setCookie(httpServletRequest,resp,COOKIE_INFO_USER_NAME,String.format("%s:%s",username,password),7*24*60*60);
            }
            httpServletRequest.getSession().setAttribute(Constants.SESSION_USER,user);
            return "redirect:/main";
        }
    }
    //注销
    @RequestMapping(value = "logout",method = RequestMethod.GET)
    public String logout(HttpServletRequest httpServletRequest){
        httpServletRequest.getSession().invalidate();
        return "login";
    }

    @RequestMapping("main")
    public String main()
    {
        return "main";
    }
}
